package com.itbaizhan;

import java.sql.Connection;
import java.sql.PreparedStatement;

/**PreparedStatement的使用*/
public class TestPreparedStatement01 {
    /*添加用户信息*/
    public void insertUsers01(String username,int userage){
        Connection connection = null;
        PreparedStatement ps = null;
        try {
            //获取连接sql对象
            connection = JdbcUtils.getConnection();
            //定义SQL语句
            //问号是占位符，由1开始计算，如果列是字符类型，也不用“”，直接写?
            String sql = "insert into users values(default,?,?)";
            //获取PreparedStatement 对象
            ps = connection.prepareStatement(sql);
            ps.setString(1,username);
            ps.setInt(2,userage);
            int i = ps.executeUpdate();
            System.out.println(i);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            JdbcUtils.closeResource(ps,connection);
        }
    }

    /*更改信息*/
    public void updateUsers01(int userid,String username,int userage){
        Connection connection = null;
        PreparedStatement ps = null;
        try{
            connection = JdbcUtils.getConnection();
            ps = connection.prepareStatement("update users set username = ?,userage = ? where userid = ?");
            ps.setString(1,username);
            ps.setInt(2,userage);
            ps.setInt(3,userid);
            int i = ps.executeUpdate();
            System.out.println(i);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            JdbcUtils.closeResource(ps,connection);
        }
    }
    //删除用户
    public void deleteUsers01(int userid){
        Connection connection = null;
        PreparedStatement ps = null;
        try{
            connection = JdbcUtils.getConnection();
            ps = connection.prepareStatement("delete from users where userid = ?");
            ps.setInt(1,userid);
            int i = ps.executeUpdate();
            System.out.println(i);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            JdbcUtils.closeResource(ps,connection);
        }
    }
}
